<script setup lang="ts">
import { PropType, ref, unref,computed, watch, onMounted } from 'vue'
import type { TableData } from '@/api/account/types'
import { Dialog } from '@/components/Dialog'
import UpdateRevenue from './UpdateRevenue.vue'
// import { ElButton, ElCard } from 'element-plus'
import { useI18n } from '@/hooks/web/useI18n'
import { getCalendarDataApi,saveScoreIcomeApi } from '@/api/account'
import type { DescriptionsSchema } from '@/components/Descriptions'

interface CalendarDayData {
  date: number
  isCurrentMonth: boolean
  fullDate: Date
}

const { t } = useI18n()

const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<TableData>>,
    default: () => null
  },
  detailSchema: {
    type: Array as PropType<DescriptionsSchema[]>,
    default: () => []
  }
})

const dialogVisible = ref(false)
const dialogTitle = ref('')
const actionType = ref('')
const selectedDay = ref<number | null>(null)
const currentDate = ref(new Date())
const selectedDayExpenditure = ref<number | undefined>(undefined)
const selectedDayScore = ref<number | undefined>(undefined)

// 格式化年月显示
const formattedMonth = computed(() => {
  const year = currentDate.value.getFullYear()
  const month = currentDate.value.getMonth() + 1
  return `${year}年${month}月`
})

// 获取当月的日历数据
const calendarData = computed<CalendarDayData[]>(() => {
  const year = currentDate.value.getFullYear()
  const month = currentDate.value.getMonth()
  
  // 获取当月第一天和最后一天
  const firstDay = new Date(year, month, 1)
  const lastDay = new Date(year, month + 1, 0)
  
  // 获取当月第一天是周几（0=周日，1=周一...）
  const firstDayOfWeek = firstDay.getDay()
  const adjustedFirstDay = firstDayOfWeek === 0 ? 6 : firstDayOfWeek - 1 // 调整为周一开始
  
  // 获取当月天数
  const daysInMonth = lastDay.getDate()
  
  // 生成日历数组
  const calendar: Array<{ date: number; isCurrentMonth: boolean; fullDate: Date }> = []
  
  // 添加上个月的尾部日期（填充空白）
  for (let i = adjustedFirstDay - 1; i >= 0; i--) {
    const prevDate = new Date(year, month, -i)
    calendar.push({
      date: prevDate.getDate(),
      isCurrentMonth: false,
      fullDate: prevDate
    })
  }
  
  // 添加当月日期
  for (let day = 1; day <= daysInMonth; day++) {
    calendar.push({
      date: day,
      isCurrentMonth: true,
      fullDate: new Date(year, month, day)
    })
  }
  
  // 添加下个月的开头日期（填充到42个格子）
  const remainingCells = 42 - calendar.length
  for (let day = 1; day <= remainingCells; day++) {
    const nextDate = new Date(year, month + 1, day)
    calendar.push({
      date: nextDate.getDate(),
      isCurrentMonth: false,
      fullDate: nextDate
    })
  }
  
  return calendar
})

// 切换到上个月
const prevMonth = () => {
  currentDate.value = new Date(currentDate.value.getFullYear(), currentDate.value.getMonth() - 1, 1)
  selectedDate.value = null // 清除选中状态
}

// 切换到下个月
const nextMonth = () => {
  currentDate.value = new Date(currentDate.value.getFullYear(), currentDate.value.getMonth() + 1, 1)
  selectedDate.value = null // 清除选中状态
}

// 周几的标签
const weekDays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']

// 存储API获取的收益数据
const profitsData = ref<Record<number, {
  score?: number, income?: number, expenditure?: number
}>>({})

// 存储API获取的统计数据
const statsData = ref({
  project: 0,
  income: 0,
  profit: 0,
  sltprj: 0,
  sltinc: 0,
  sltprf: 0
})

// 当前选中的日期（存储完整的Date对象）
const selectedDate = ref<Date | null>(null)

// 获取月度收益数据
const fetchMonthlyProfits = async () => {
  const year = currentDate.value.getFullYear()
  const month = currentDate.value.getMonth()
  
  // 格式化为 YYYY-MM-DD 格式
  const startDate = `${year}-${(month + 1).toString().padStart(2, '0')}-01`
  const endDate = `${year}-${(month + 1).toString().padStart(2, '0')}-${new Date(year, month + 1, 0).getDate().toString().padStart(2, '0')}`
  
  try {
    const res = await getCalendarDataApi({
      id: props.currentRow?.id || 0,
      beginday: startDate,
      endday: endDate
    })
    
    // 更新统计数据
    if (res && res.data) {
      statsData.value = {
        project: res.data.project || 0,
        income: res.data.income || 0,
        profit: res.data.profit || 0,
        sltprj: res.data.sltprj || 0,
        sltinc: res.data.sltinc || 0,
        sltprf: res.data.sltprf || 0
        
      }
    }
    // 处理API返回的收益数据
    if (res?.data?.items) {
      const processedData: Record<number, {score?: number, income?: number, expenditure?: number}> = {}
      res.data.items.forEach((item: any) => {
        const day = new Date(item.day).getDate()
        processedData[day] = {
          score: item.score ? +item.score : undefined,
          income: item.income ? +item.income : undefined,
          expenditure: item.expenditure ? +item.expenditure : undefined
        }
      })
      profitsData.value = processedData
    } else {
      profitsData.value = {}
    }
  } catch (error) {
    console.error('获取日历数据失败:', error)
    // 如果API调用失败，清空数据
    profitsData.value = {}
  }
}
const writeRef = ref<ComponentRef<typeof UpdateRevenue>>()

const saveLoading = ref(false)
const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  console.log('======',formData)
  if (formData) {
    saveLoading.value = true
    const res = await saveScoreIcomeApi(formData)
      .catch(() => {})
      .finally(() => {
        saveLoading.value = false
      })
    if (res) {
      dialogVisible.value = false
      // currentPage.value = 1
      fetchMonthlyProfits()
    }
  }
}
// 获取指定日期的收益数据
const getDayData = (day: number) => {
  return profitsData.value[day] || {}
}
const revenue = (dayData: any) => {
  // 检查日期是否大于当前日期
  const currentDateObj = new Date()
  const today = new Date(currentDateObj.getFullYear(), currentDateObj.getMonth(), currentDateObj.getDate())
  const selectedDateObj = new Date(dayData.fullDate.getFullYear(), dayData.fullDate.getMonth(), dayData.fullDate.getDate())
  
  // 如果选择的日期大于今天，则不能点击
  if (selectedDateObj > today) {
    return
  }
  
  // 设置选中日期（使用完整的Date对象）
  selectedDate.value = dayData.fullDate
  
  // 获取当天的expenditure值
  const dayData_expenditure = profitsData.value[dayData.date]?.expenditure
  selectedDayExpenditure.value = dayData_expenditure
  
  // 获取当天的score值
  const dayData_score = profitsData.value[dayData.date]?.score
  selectedDayScore.value = dayData_score
  
  // 构建完整的年月日日期字符串
  const fullDate = `${currentDate.value.getFullYear()}年${(currentDate.value.getMonth() + 1).toString().padStart(2, '0')}月${dayData.date.toString().padStart(2, '0')}日`
  dialogTitle.value = t('account.UpdateRevenue') + fullDate
  
  actionType.value = 'updateRevenue'
  selectedDay.value = dayData.date
  dialogVisible.value = true
}

// 监听月份变化，重新获取数据
watch(currentDate, () => {
  fetchMonthlyProfits()
}, { deep: true })

// 组件挂载时获取初始数据并选中当天
onMounted(() => {
  fetchMonthlyProfits()
  // 默认选中当天
  const today = new Date()
  const currentYear = currentDate.value.getFullYear()
  const currentMonth = currentDate.value.getMonth()
  
  // 如果当天在当前显示的月份内，则选中
  if (today.getFullYear() === currentYear && today.getMonth() === currentMonth) {
    // 直接创建对应的日期对象，确保与日历数据中的格式一致
    selectedDate.value = new Date(currentYear, currentMonth, today.getDate())
  }
})
</script>

<template>
  <div class="calendar-container">
    <div class="user-brief">
      <span class="item"><span class="label">UID：</span><span class="value">{{ (props.currentRow as any)?.uid || '-' }}</span></span>
      <span class="item"><span class="label">操手：</span><span class="value">{{ (props.currentRow as any)?.oprName || '-' }}</span></span>
    </div>
    <!-- 统计信息卡片 -->
    <div class="stats-row">
      <div class="stat-card">
        <div class="stat-label">{{ t('account.projectTotal') || '项目总数' }}</div>
        <div class="stat-value">{{ statsData.project }}</div>
      </div>
      <div class="stat-card">
        <div class="stat-label">{{ t('account.totalRevenue') || '空投总收益' }}</div>
        <div class="stat-value">{{ statsData.income.toFixed(2) }}</div>
      </div>
      <div class="stat-card">
        <div class="stat-label">{{ t('account.totalProfit') || '总利润' }}</div>
        <div class="stat-value">{{ statsData.profit.toFixed(2) }}</div>
      </div>
    </div>

    <!-- 顶部信息栏 -->
    <div class="header-row">
      <!-- 左侧：年月切换器 -->
      <div class="month-navigator">
        <span class="nav-arrow" @click="prevMonth"><</span>
        <span class="month-display">{{ formattedMonth }}</span>
        <span class="nav-arrow" @click="nextMonth">></span>
      </div>
      
      <!-- 右侧：项目信息 -->
      <div class="project-info">
        <span>累计项目</span>
        <span class="revenue-info"> {{  statsData.sltprj}}</span>|
        <span>累计空投收益</span>
        <span class="revenue-info"> ${{ statsData.sltinc.toFixed(2) }}</span>|
        <span>累计利润</span>
        <span class="profit-info"> ${{ statsData.sltprf.toFixed(2) }}</span>
      </div>
    </div>

    <!-- 日历组件 -->
    <div class="calendar-wrapper">
      <!-- 星期标题 -->
      <div class="week-header">
        <div v-for="day in weekDays" :key="day" class="week-day">
          {{ day }}
        </div>
      </div>
      
      <!-- 日期网格 -->
      <div class="calendar-grid">
        <div
          @click="revenue(dayData)"
          v-for="(dayData, index) in calendarData"
          :key="index"
          class="calendar-cell"
          :class="{
            'other-month': !dayData.isCurrentMonth,
            'current-month': dayData.isCurrentMonth,
            'selected': selectedDate && dayData.fullDate.getTime() === selectedDate.getTime(),
            'disabled': (() => {
              const currentDateObj = new Date()
              const today = new Date(currentDateObj.getFullYear(), currentDateObj.getMonth(), currentDateObj.getDate())
              const selectedDateObj = new Date(dayData.fullDate.getFullYear(), dayData.fullDate.getMonth(), dayData.fullDate.getDate())
              return selectedDateObj > today
            })()
          }"
        >
          <div class="date-number">{{ dayData.date }}<span v-if="dayData.isCurrentMonth && getDayData(dayData.date).score !== undefined"  class="custom-text">{{ getDayData(dayData.date).score }}</span></div>
          <div class="profit-container" style="display: flex; flex-direction: column; gap: 4px;">
            <div 
              v-if="dayData.isCurrentMonth && getDayData(dayData.date).income !== undefined" 
              class="profit-amount profit-positive"
            >
              {{ getDayData(dayData.date).income }}
            </div>
            <div 
              v-if="dayData.isCurrentMonth && getDayData(dayData.date).expenditure !== undefined" 
              class="profit-amount profit-negative"
            >
              {{ getDayData(dayData.date).expenditure }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <Dialog v-model="dialogVisible" width="600px" :maxHeight="400">
    <template #title>
      <span>{{ t('account.UpdateRevenue') }}
        <span style="color: #409eff;">
        {{ currentDate.getFullYear() }}-{{ (currentDate.getMonth() + 1).toString().padStart(2, '0') }}-{{ selectedDay?.toString().padStart(2, '0') }}
      </span>
      </span>
      
    </template>
    <UpdateRevenue
      v-if="actionType === 'updateRevenue'"
      ref="writeRef"
      :current-row="currentRow"
      :selected-day="selectedDay || undefined"
      :current-date="currentDate"
      :selected-day-expenditure="selectedDayExpenditure"
      :selected-day-score="selectedDayScore"
    />
    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        {{ t('exampleDemo.save') }}
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
</template>

<style scoped>
.calendar-container {
  padding: 20px;
  background: #fff;
  font-size: 14px;
}

/* 顶部UID/操手信息 */
.user-brief {
  display: flex;
  align-items: center;
  gap: 120px;
  margin-bottom: 10px;
  margin-top: -20px;
}

.user-brief .item {
  white-space: nowrap;
}

.user-brief .label {
  color: inherit;
  font-weight: 700;
  margin-right: 6px;
}

.user-brief .value {
  color: inherit;
  font-weight: 700;
}

/* 统计信息卡片 */
.stats-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  flex: 1;
  text-align: center;
  padding: 20px;
  background: #fff;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
  white-space: nowrap;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #409eff;
  white-space: nowrap;
}

/* 顶部信息栏 */
.header-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1px;
  padding: 0px;
  background: #f8f9fa;
  border-radius: 8px;
}

/* 年月切换器 */
.month-navigator {
  display: flex;
  align-items: center;
  gap: 2px;
}

.nav-arrow {
  font-size: 18px;
  font-weight: bold;
  color: #409eff;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.2s;
  user-select: none;
}

.nav-arrow:hover {
  background: #f0f9ff;
  color: #1890ff;
}

.month-display {
  font-size: 16px;
  font-weight: 600;
  /* color: #333; */
  /* min-width: 120px; */
  text-align: center;
  white-space: nowrap;
}

/* 项目信息 */
.project-info {
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 10px;
  font-size: 16px;
}

/* .project-name {
  font-size: 14px;
  font-weight: 600;
  color: #ccc;
  white-space: nowrap;
} */

.revenue-info {
  font-size: 14px;
  color: #1890ff;
  font-weight: 500;
  white-space: nowrap;
}

.profit-info {
  font-size: 14px;
  color: #1890ff;
  font-weight: 500;
  white-space: nowrap;
}

/* 日历组件 */
.calendar-wrapper {
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  overflow: hidden;
}

/* 星期标题 */
.week-header {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  background: #fafafa;
  border-bottom: 1px solid #e8e8e8;
}

.week-day {
  padding: 12px;
  text-align: center;
  font-weight: 600;
  color: #666;
  border-right: 1px solid #e8e8e8;
  font-size: 14px;
}

.week-day:last-child {
  border-right: none;
}

/* 日期网格 */
.calendar-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
}

.calendar-cell {
  padding: 8px;
  text-align: center;
  border-right: 1px solid #e8e8e8;
  border-bottom: 1px solid #e8e8e8;
  cursor: pointer;
  transition: all 0.2s;
  min-height: 60px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  gap: 4px;
}

.date-number {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 2px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.custom-text {
  font-size: 11px;
  color: #409eff;
  text-align: right;
  margin-left: auto;
}

.profit-container {
  min-height: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.profit-amount {
  font-size: 11px;
  font-weight: bold;
  padding: 2px 4px;
  border-radius: 3px;
  white-space: nowrap;
}

.profit-positive {
  color: #52c41a;
  background: #f6ffed;
}

.profit-negative {
  color: #ff4d4f;
  background: #fff2f0;
}

.calendar-cell:last-child {
  border-right: none;
}

.calendar-cell:hover {
  background: #f0f9ff;
}

.calendar-cell.disabled {
  cursor: not-allowed;
  opacity: 0.5;
  background: #f5f5f5;
}

.calendar-cell.disabled:hover {
  background: #f5f5f5;
}

.calendar-cell.selected {
  background: #409eff;
  color: #fff;
  border: 2px solid #1890ff;
  position: relative;
  z-index: 1;
}

.calendar-cell.selected .date-number {
  color: #fff;
  font-weight: bold;
}

.calendar-cell.selected .custom-text {
  color: #fff !important;
}

.calendar-cell.selected .profit-amount {
  color: #fff !important;
  background: rgba(255, 255, 255, 0.2) !important;
}

.calendar-cell.other-month.selected {
  color: #fff;
  background: #409eff;
  border: 2px solid #1890ff;
}

.calendar-cell.other-month.selected .date-number {
  color: #fff;
  font-weight: bold;
}

.current-month {
  color: #333;
  font-weight: 500;
  font-size: 14px;
}

.other-month {
  color: #ccc;
  font-size: 14px;
}

/* 按钮样式调整 */
:deep(.el-button.is-circle) {
  width: 32px;
  height: 32px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
